package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.file-path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file) {//file时一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会删除
        //使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString();
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接为新的文件名
        fileName = fileName + substring;

        File dir = new File(path);
        //判断当前目录是否存在
        if(!dir.exists()){
            //不存在时创建该目录
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(path + File.separator + fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传文件失败");
        }
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //读取磁盘中的文件
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(),"ISO-8859-1"));
        FileInputStream fileInputStream = new FileInputStream(path + File.separator + name);
        IoUtil.copy(fileInputStream, response.getOutputStream());
        fileInputStream.close();
    }
}
